package com.lepu.app.fun.index.activity;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.app.utils.LoginUtil;
import com.app.utils.ObserverConst;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.EmojiFilter;
import com.core.lib.utils.ObserverManager;
import com.core.lib.utils.main.DateUtilBase;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.widget.MyDialog;
import com.lepu.app.fun.index.bean.BeanIndexFileLog;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewRightButtonListener;
import com.lepu.pasm.R;

public class IndexFileLogAddActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, OnTopbarNewRightButtonListener, AsyncRequest{
	private static final String REQUEST_DATA = "request_data";
	private EditText weightEdit;
	private EditText heartEdit;
	private EditText sbpEdit;
	private EditText dbpEdit;
	private EditText bloodEdit;
	private EditText noteEdit;
	
	private TextView bloodText;
	private LinearLayout bloodLayout;
	
	private String[] mMealArray;
	private int[] mMealIndexArray;
	private int mMeal = 1; //默认空腹血糖
	private int mSaveType = 1; //添加  or 编辑

	private BeanIndexFileLog mBeanFileLog;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.index_file_log_add_activity);

		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finish(true);
	}
	
	@Override
	public void onTopbarLeftLayoutSelected() {
		finish(true);
	}

	@Override
	public void onTopbarRightButtonSelected() {
		if(mSaveType == 1){
			save();
		}else if(mSaveType == 2){
			update();
		}
		
	}

	/**
	 * 初始化方法
	 */
	private void init() {
		// topbar
		CustomTopBarNew topbar = (CustomTopBarNew) findViewById(R.id.topbar);
		topbar.setTopbarTitle("写日志");
		topbar.setRightText("完成");
		topbar.setonTopbarNewLeftLayoutListener(this);
		topbar.setOnTopbarNewRightButtonListener(this);
		
		weightEdit = (EditText) findViewById(R.id.weightEditText);
		heartEdit = (EditText) findViewById(R.id.heartEditText);
		sbpEdit = (EditText) findViewById(R.id.sbpEditText);
		dbpEdit = (EditText) findViewById(R.id.dbpEditText);
		bloodEdit = (EditText) findViewById(R.id.bloodEditText);
		noteEdit = (EditText) findViewById(R.id.noteEditText);
		bloodText = (TextView) findViewById(R.id.bloodTextView);
		bloodLayout = (LinearLayout) findViewById(R.id.bloodLayout);
		
		mMealArray = getResources().getStringArray(R.array.blood_select_test_time_array);
		mMealIndexArray = getResources().getIntArray(R.array.blood_select_test_time_index_array);
		
		bloodLayout.setOnClickListener(viewClick);

		noteEdit.setFilters(new InputFilter[]{new EmojiFilter()
				,new InputFilter.LengthFilter(400)});
		
		mBeanFileLog = (BeanIndexFileLog) getIntent().getSerializableExtra("fileLog");
		if(mBeanFileLog != null){
			mSaveType = 2;
			weightEdit.setText(mBeanFileLog.Weight);
			heartEdit.setText(mBeanFileLog.HeartRate);
			sbpEdit.setText(mBeanFileLog.SBP);
			dbpEdit.setText(mBeanFileLog.DBP);
			bloodEdit.setText(mBeanFileLog.BloodGlucose);
			noteEdit.setText(mBeanFileLog.Description);
			
			String[] mealArray = getResources().getStringArray(R.array.blood_select_test_time_array);
			bloodText.setText(mealArray[mBeanFileLog.BloodGlucoseType-1]);
			mMeal = mBeanFileLog.BloodGlucoseType;
		}
	}
	
	View.OnClickListener viewClick = new View.OnClickListener() {
		@Override
		public void onClick(View arg0) {
			showMealDialog();
		}
	};
	
	private void showMealDialog() {
		MyDialog dialog = new MyDialog(this).setSimpleItems(mMealArray,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

						bloodText.setText(mMealArray[which]);
						mMeal = mMealIndexArray[which];
					}
				});
		dialog.create(null).show();
	}
	
	// 保存数据
	public void save() {
		String weight = weightEdit.getText().toString();
		String heart = heartEdit.getText().toString();
		String sbp = sbpEdit.getText().toString();
		String dbp = dbpEdit.getText().toString();
		String blood = bloodEdit.getText().toString();
		String note = noteEdit.getText().toString();
		
		if(TextUtils.isEmpty(weight)&&
		   TextUtils.isEmpty(heart)&&
		   TextUtils.isEmpty(sbp)&&
		   TextUtils.isEmpty(dbp)&&
		   TextUtils.isEmpty(blood)&&
		   TextUtils.isEmpty(note)){
				UIHelper.showToast(this, "请填写数据");
				return;
		}
		
		if (!TextUtils.isEmpty(weight)) {
			if (Integer.valueOf(weight) < 30 || Integer.valueOf(weight) > 150) {
				UIHelper.showToast(this, "请输入30-150kg 体重");
				return;
			}
		}

		if (!TextUtils.isEmpty(heart)) {
			if (Integer.valueOf(heart) < 40 || Integer.valueOf(heart) > 180) {
				UIHelper.showToast(this, "请输入40-180次/分钟 心率");
				return;
			}
		}

		if (!TextUtils.isEmpty(sbp)) {
			if (Integer.valueOf(sbp) < 30 || Integer.valueOf(sbp) > 200) {
				UIHelper.showToast(this, "请输入30-200mmHg 高血压");
				return;
			}
		}
		if (!TextUtils.isEmpty(dbp)) {
			if (Integer.valueOf(dbp) < 20 || Integer.valueOf(dbp) > 150) {
				UIHelper.showToast(this, "请输入20-150mmHg 低血压");
				return;
			}
		}

		if (!TextUtils.isEmpty(blood)) {
			if (Double.valueOf(blood) < 1.0 || Double.valueOf(blood) > 34.0) {
				UIHelper.showToast(this, "请输入1.0-34.0mmol/L 血糖");
				return;
			}
		}
		
		String url = Setting.getIndexFileLogUp();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			
			JSONArray jsonArray = new JSONArray();
				
			JSONObject json = new JSONObject();
			json.put("BloodGlucoseType", mMeal);
			json.put("BloodGlucose",blood);
			json.put("Weight",weight);
			json.put("SBP",sbp);
			json.put("DBP",dbp);
			json.put("HeartRate",heart);
			json.put("RecordDate",DateUtilBase.stringFromDate(new Date(),DateUtilBase.DATE_ALL_ALL));
			json.put("Description",note);

			jsonArray.put(json);
			params.put("DataList", jsonArray);

		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post_main(url, map, null, this,REQUEST_DATA, true, true, false);
		showProgressDialog();
	}
	
	// 更新数据
	public void update() {
		String weight = weightEdit.getText().toString();
		String heart = heartEdit.getText().toString();
		String sbp = sbpEdit.getText().toString();
		String dbp = dbpEdit.getText().toString();
		String blood = bloodEdit.getText().toString();
		String note = noteEdit.getText().toString();
		
		if(TextUtils.isEmpty(weight)&&
				TextUtils.isEmpty(heart)&&
				TextUtils.isEmpty(sbp)&&
				TextUtils.isEmpty(dbp)&&
				TextUtils.isEmpty(blood)&&
				TextUtils.isEmpty(note)){
			UIHelper.showToast(this, "请填写数据");
			return;
		}
		
		String url = Setting.getIndexFileLogUpdate();
		
		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();
		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);
			
			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());
			params.put("HRID", mBeanFileLog.HRID);
			
			JSONObject json = new JSONObject();
			json.put("BloodGlucoseType", mMeal);
			json.put("BloodGlucose",blood);
			json.put("Weight",weight);
			json.put("SBP",sbp);
			json.put("DBP",dbp);
			json.put("HeartRate",heart);
			json.put("RecordDate",DateUtilBase.stringFromDate(new Date(),DateUtilBase.DATE_ALL_ALL));
			json.put("Description",note);
			
			params.put("HealthRecordData", json);
			
		} catch (Exception e) {
		}
		map.put("ht", params);
		ApiClient.http_post_main(url, map, null, this,REQUEST_DATA, true, true, false);
		showProgressDialog();
	}
	
	@Override
	public void RequestComplete(Object arg0, Object arg1) {
		if(arg0.equals(REQUEST_DATA)){
			hideProgressDialog();
			ObserverManager.getInstance().notify(ObserverConst.NOTIFY_FILE_LOG_CHANGE, null, null);
			finish(true);
		}
	}

	@Override
	public void RequestError(Object arg0, int arg1, String arg2) {
		if(arg0.equals(REQUEST_DATA)){
			hideProgressDialog();
		}
	}


}
